<template>
  <div class="pages transfer">
    <div class="pageLevel" v-if="!sub">
      <div class="operationBox tableSearch" style=" margin-left:30px;">
        <el-button type="primary" @click="submitForm('formdata')" :disabled="entered" size="mini">保存</el-button>
        <el-button type="primary" @click="openGoodsdialog() " :disabled="entered" size="mini">批量添加商品</el-button>
        <el-button type="primary" @click="deletAll_goods()" :disabled="entered" size="mini">批量删除商品</el-button>
      </div>
      <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
        <el-row>
          <el-col :span="8">
            <el-form-item label="出库仓库：" prop="outRepertoryId">
              <el-select size="small" style="width:200px" @change="getwarehouseName(formdata.outRepertoryId,'out')" v-model="formdata.outRepertoryId" placeholder="请先选择出库仓库">
                <el-option v-for="item in options" :key="item.index" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库：" prop="inRepertoryId">
              <el-select size="small" style="width:200px" @change="getwarehouseName(formdata.inRepertoryId,'in')" v-model="formdata.inRepertoryId" placeholder="请先选择入库仓库">
                <el-option v-for="item in options" :key="item.index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据日期：" prop="orderDate">
              <el-date-picker v-model="formdata.orderDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择单据日期" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table :data="tableData" stripe style="width: 100%" @selection-change="changeFun_good_table">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column type="index" label="#" width="55"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="name" label="商品" align="center" width="200">
          </el-table-column>
          <el-table-column prop="goodsNum" label="数量" align="center" width="150">
            <template slot-scope="scope">
              <input class="commonInput" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="1" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else if(this.value){this.value=parseInt(this.value.replace(/\D/g,''))}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
            </template>
          </el-table-column>

          <el-table-column prop="parameter" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in  scope.row.parameter" :key="index" v-if='item'>
                <span>{{item.paramName}} :</span>
                <span>{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsBatchNumber" label="商品批次" align="center">
             <template slot-scope="scope" >
             <span v-if="scope.row.isBatch == '1'">{{scope.row.goodsBatchNumber}}</span>
             <span v-if="scope.row.isBatch =='0'">{{"---"}}</span>
            </template>
          </el-table-column>
          <!-- 集团订单新加功能5/31 -->
          <el-table-column prop="dateInProduced" label="生产日期" align="center" width="100">
             <template slot-scope="scope" >
             <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
             <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="goodsPrice" label="单价" align="center"> </el-table-column>
          <el-table-column prop="goodsAmount" label="总价" align="center">
            <template slot-scope="scope">
              <span>{{(Number(scope.row.goodsPrice) * (Number(scope.row.goodsNum) ? (Number(scope.row.goodsNum)) : 0)).toFixed(2)}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.name" @click="handleCancel(scope.$index)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="th-right">
        <el-form :model="formdata" :rules="rules" label-width="120px" size="mini">
          <el-row>
            <el-col :span="12">
              <el-form-item label="操作员：">
                <el-input v-model="formdata.creater" disabled></el-input>
              </el-form-item>
              <el-form-item label="备注：">
                <el-input v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="总计：" prop="priceTotal">
                <el-input v-model="formdataTotal" disabled></el-input>
              </el-form-item>
              <!-- <el-form-item label="运费：" prop="freight">
              <el-input v-model="formdata.freight" type="text" min="0" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"></el-input>
            </el-form-item>
            <el-form-item label="税：" prop="taxAmount">
              <el-input v-model="formdata.taxAmount" type="text" min="0" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"></el-input>
            </el-form-item>
            <el-form-item label="应付总计：">
              <el-input v-model="formdataAllTotal" disabled></el-input>
            </el-form-item> -->
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 商品选择弹出框 -->
      <el-dialog v-loading.body="loading" title="商品选择" class="addshopname" :visible.sync="dialogTableVisible_good" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
        <i class="el-icon-close icon" @click="dialogTableVisible_good=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="save_good">选择</el-button>
          <el-button size="mini" @click="closes">取消</el-button>
        </div>
        <div class="tableSearch tableSearchs">
          <i class="el-input__icon el-icon-search" @click="searchSelect"></i>
          <el-form label-width="100px" class="demo-ruleForm">
            <el-form-item label="" label-width="15px">
              <el-input class="input" v-model="selectdatas.keyword" size="small" placeholder="输入商品名称">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="goodArray" stripe border ref="multipleTable" tooltip-effect="dark" @selection-change="changeFun_good">
          <el-table-column type="selection" width="55" :selectable='selectable'></el-table-column>
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="name" label="商品" align="center"></el-table-column>
          <el-table-column prop="goodsBatchNumber" label="商品批次" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.isBatch=='1'">{{scope.row.goodsBatchNumber}}</span>
              <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
            </template>
          </el-table-column>
          <!-- 集团订单新加功能5/31 -->
          <el-table-column prop="dateInProduced" label="生产日期" align="center" width="100">
             <template slot-scope="scope" >
             <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
             <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsPrice" label="单价" align="center"> </el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="parameter" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in  scope.row.parameter" :key="index" v-if='item'>
                <span>{{item.paramName}} :</span>
                <span>{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsQuantity" label="库存结余" align="center"></el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChange_good" @current-change="handleCurrentChange_good" :current-page="currentpage_good" :page-sizes="[20,40]" :page-size="pageSize_good" layout="total, sizes, prev, pager, next, jumper" :total="total_good">
          </el-pagination>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import sdInput from "@/components/SdInput";
import { mapState } from "vuex";
import u from "@/util";
import { getRepositoryListPage, findGoodsRepositoryByRepositoryId, allotGoods } from "@/api";
export default {
  components: { sdInput },
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      userInfo: state => state.userInfo,
      sub: state => state.sub,
      linkName: state => state.linkName,
      mobile: state => state.mobile,
      companyName: state => state.companyName,
      userId: state => state.userId,
    }),
    formdataTotal: function() {
      let totalPrice = 0;
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsAmount =
          this.tableData[i].goodsPrice * this.tableData[i].goodsNum;
        totalPrice += this.tableData[i].goodsPrice * this.tableData[i].goodsNum;
      }
      this.formdata.purchaseAmount = totalPrice.toFixed(2);
      return isNaN(totalPrice) ? 0 : totalPrice.toFixed(2);
    }
  },
  data() {
    return {
      entered: false,
      id: "",
      userInfos: "",
      dataa: [],
      options: [],
      status: true,
      //商品输入框
      selectdata: {
        keyword: ""
      },
      selectdatas: {
        keyword: ""
      },
      consignee: "",
      linkman: "",
      address: "",
      tableData: [],
      //新增表单
      formdata: {
        orderDate: "",
        purchaseinCode: "",
        creater: "",
        remark: "",
        outRepertoryId: "",
        inRepertoryId: ""
      },
      dialogTableVisible_good: false,
      selection_good: [],
      selection_good_table: [],
      goodArray: [],
      pageSize_good: 20,
      currentpage_good: 1,
      total_good: 0,
      loading: true,
      rules: {
        outRepertoryId: [
          { required: true, message: "请选择出库仓库", trigger: "blur" }
        ],
        inRepertoryId: [
          { required: true, message: "请选择入库仓库", trigger: "blur" }
        ],
        orderDate: [
          { required: true, message: "请选择收货时间", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.init();
    this.data();
    this.repertory();
  },
  methods: {
    numall: u.numall,
    openGoodsdialog: function() {
      if (this.formdata.outRepertoryId) {
        this.dialogTableVisible_good = true;
        this.$nextTick(function () {
          this.getGoods(this.pageSize_good, this.currentpage_good);
        })
      } else {
        this.$message({
          type: "error",
          message: "请先选择仓库"
        });
      }
    },
    deletAll_goods() {
      let self = this;
      this.tableData = this.tableData.filter(function(item) {
        return self.selection_good_table.indexOf(item) == -1;
      });
    },
    getwarehouseName(val, type) {
      if (this.formdata.outRepertoryId == this.formdata.inRepertoryId) {
        this.$message({
          type: "error",
          message: "不可选择同一个"
        });
        if (type == "out") {
          this.formdata.outRepertoryId = "";
        } else {
          this.formdata.inRepertoryId = "";
        }
        return false;
      }
      this.dataa.forEach(item => {
        if (item.openingInventoryState == "0" && item.id == val) {
          this.entered = true;
          this.$message({
            type: "error",
            message: "该仓库未录入期初库存"
          });
          if (type == "out") {
            this.formdata.outRepertoryId = "";
          } else {
            this.formdata.inRepertoryId = "";
          }
        } else {
          this.entered = false;
        }
      });
      if (val && type == "out") {
        this.tableData = [];
      }
    },
    repertory() {
      //仓库下拉
      let datass = {
        shopId: this.merchantId,
        status: "0"
      };
      getRepositoryListPage(datass).then(res => {
        this.dataa = res.data.list;
        for (let i = 0; i < this.dataa.length; i++) {
          let a = {
            id: this.dataa[i].id,
            name: this.dataa[i].repositoryName
          };
          this.options.push(a);
        }
      });
    },
    searchSelect() {
      this.selectdata.keyword = this.selectdatas.keyword;
       this.currentpage_good=1
      this.getGoods(this.pageSize_good, this.currentpage_good);
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },
    //--------默认当前时间
    data(picker) {
      new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10);
      const date = new Date();
      var datas = date.setTime(date.getTime());
      var datase = u.foryear(parseInt(datas));
      this.formdata.orderDate = datase;
    },
    //默认当前操作员
    init() {
      if (this.linkName != undefined&&this.linkName != "") {
        this.userInfos = this.linkName;
      } else {
        this.userInfos = this.mobile;
      }
      this.formdata.creater = this.userInfos;
    },
    getGoods(pageSize, pageNum) {
      this.loading = true;
      let data = {
        repositoryId: this.formdata.outRepertoryId,
        pageSize: pageSize,
        pageNum: pageNum,
        goodsName: this.selectdatas.keyword,
        shopId: this.merchantId
      };
        findGoodsRepositoryByRepositoryId(data).then(res => {
          this.goodArray = res.data.list;
          this.total_good = res.data.pageTotal;
          this.loading = false;
        });
    },
    //---------新增保存
    handleSave() {
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsName = this.tableData[i].name;
        this.tableData[i].goodsOrganizationSkuId = this.tableData[i].id;
        //this.tableData[i].goodsPrice = this.tableData[i].purchasePrice;
        this.tableData[i].goodsSpec = this.tableData[i].parameter;
        this.tableData[i].goodsId = this.tableData[i].id;
        this.tableData[i].goodsUnit = this.tableData[i].goodsUnitId;
        this.tableData[i].goodsAmount = (
          +this.tableData[i].goodsNum * +this.tableData[i].goodsPrice
        ).toFixed(2);
        if (this.tableData[i].goodsNum <= 0) {
          this.$message({
            type: "error",
            message: "商品数量不能小于等于0"
          });
          return false;
        }
      }
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].id == this.formdata.outRepertoryId) {
          this.formdata.warehouseName = this.options[i].name;
        }
      }
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].id == this.formdata.inRepertoryId) {
          this.formdata.warehouseName = this.options[i].name;
        }
      }
      let datas = {
        outRepertoryId: this.formdata.outRepertoryId,
        inRepertoryId: this.formdata.inRepertoryId,
        shopId: this.merchantId,
        shopName: this.companyName,
        creater: this.userId,
        outAmount: this.formdataTotal,
        remark: this.formdata.remark,

        goodsList: JSON.stringify(this.tableData)
      };
      if (this.tableData.length > 0) {
        allotGoods(datas).then(res => {
          if (res.code == "200") {
            this.$message({
              type: "success",
              message: res.msg
            });
            this.tableData = [];
            this.formdata.outRepertoryId = "";
            this.formdata.inRepertoryId = "";
            this.formdata.remark = "";
            this.getGoods(this.pageSize_good, 1);
          }
        });
      } else {
        this.$message({
          type: "error",
          message: "请添加商品"
        });
      }
    },
    save_good() {
      if (this.selection_good.length === 0) {
        this.$message({
          type: "error",
          message: "请先选择商品!"
        });
      } else {
        this.tableData = this.tableData.concat(this.selection_good);
        this.tableData = this.uniq(this.tableData);
        this.closes();
      }
    },
    closes() {
      this.dialogTableVisible_good = false;
      this.$refs.multipleTable.clearSelection();
      this.goodArray = [];
    },
    uniq(arr) {
      let newArr = [arr[0]];
      for (let i = 1; i < arr.length; i++) {
        let repeat = false;
        for (let j = 0; j < newArr.length; j++) {
          if (
            arr[i].id === newArr[j].id &&
            arr[i].isBatch == "0" &&
            newArr[j].isBatch == "0"
          ) {
            repeat = true;
            break;
          } else {
          }
        }
        if (!repeat) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },
    changeFun_good(val) {
      if (val) {
        this.selection_good = val;
      } else {
        this.selection_good = [];
      }
    },
    changeFun_good_table(val) {
      if (val) {
        this.selection_good_table = val;
      } else {
        this.selection_good_table = [];
      }
    },
    handleCancel(index) {
      this.tableData.splice(index, 1);
    },
    handleSizeChange_good(val) {
      this.pageSize_good = val;
      this.currentpage_good=1
      this.getGoods(val, this.currentpage_good);
    },
    handleCurrentChange_good(val) {
      this.currentpage_good=val;
      this.getGoods(this.pageSize_good, val);
    },
    selectable(row, index) {
      if (+row.goodsQuantity < 1 && row.isBatch > 0) {
        return false;
      } else {
        return true;
      }
    }
  }
};
</script>
<style scoped>
.th-right {
  width: 50%;
  min-width: 300px;
  float: right;
  margin-top: 20px;
}
.tableSearchs {
  position: relative;
}
.tableSearchs .el-input__icon {
  position: absolute;
  top: 12px;
  left: 190px;
  z-index: 10;
  width: 25px;
  height: 35px;
}
</style>
<style>
.el-input__inner {
  padding: 0 20px;
}
</style>


